import os
import re

from EnvironmentFile import EnvironmentFile


class Interface:
    def __init__(self, env_file: EnvironmentFile, name: str):
        self.name = name
        self.env_file = env_file
        if not self.env_file.environment_exist(name):
            raise ValueError(f"Environment '{name}' does not exist")
        self.env = self.env_file.get_environment(name)
        self.os_add_environments(self.env["variables"])

    #############################################
    @staticmethod
    def execute(cmd: str) -> int:
        return os.system(cmd)

    @staticmethod
    def os_add_environments(env_dict: dict):
        for key, value in env_dict.items():
            if key not in os.environ.keys():
                os.environ[key] = ""
            os_env = os.environ[key].split(";")
            os_env = [i for i in os_env if i != "." and i != ""]
            for v in value:
                os_env.append(v)
            os.environ[key] = ";".join(os_env)

    @staticmethod
    def os_remove_environments(env_dict: dict):
        for key, value in env_dict.items():
            if key not in os.environ.keys():
                raise ValueError(f"Variable '{key}' does not exist")
            os_env = os.environ[key].split(";")
            os_env = [i for i in os_env if i != "." and i != ""]
            for v in value:
                os_env.remove(v)
            os.environ[key] = ";".join(os_env)

    @staticmethod
    def show_os_var():
        print()
        print("Current OS variables:")
        for key, value in os.environ.items():
            print(f"\t{key}")
            for v in value.split(";"):
                print(f"\t\t{v}")

    def show_var(self):
        print()
        print("Current variables:")
        for key, value in self.env["variables"].items():
            print(f"\t{key}")
            for v in value:
                print(f"\t\t{v}")

    #############################################
    def syscmd(self, cmd: str):
        match_obj = re.match(r"@\s*ADD\s*(.*?)\s*TO\s*(.*)", cmd)
        if match_obj:
            key = match_obj.group(2).replace('"', "")
            value = match_obj.group(1).replace('"', "")
            self.env_file.append_variable(self.name, key, value)
            self.os_add_environments({key: [value]})
            return

        match_obj = re.match(r"@\s*REMOVE\s*(.*?)\s*FROM\s*(.*)", cmd)
        if match_obj:
            key = match_obj.group(2).replace('"', "")
            value = match_obj.group(1).replace('"', "")
            self.env_file.remove_variable(self.name, key, value)
            self.os_remove_environments({key: [value]})
            return

        match_obj = re.match(r"@\s*DESCRIBE\s*(.*)", cmd)
        if match_obj:
            description = match_obj.group(1).replace('"', "")
            self.env_file.set_description(self.name, description)
            return
        match_obj = re.match(r"@\s*CD\s*(.*)", cmd)
        if match_obj:
            new_dir = match_obj.group(1).replace('"', "")
            if os.path.exists(new_dir):
                os.chdir(new_dir)
            return

        if re.match(r"@\s*LISTVAR\s*", cmd):
            self.show_var()
            return

        if re.match(r"@\s*LISTOSVAR\s*", cmd):
            self.show_os_var()
            return



        print(
            "Usage:\n"
            "@ ADD <value> TO <key>\n"
            "@ REMOVE <value> FROM <key>\n"
            "@ DESCRIBE <description>\n"
            "@ CD <dir>\n"
            "@ LISTVAR\n"
            "@ LISTOSVAR\n"
        )

    def interactive(self):
        while True:
            cmd = input(f"『{self.name}』{os.getcwd()}> ")
            if cmd == "exit":
                return
            elif cmd.startswith("@"):
                self.syscmd(cmd)
            else:
                self.execute(cmd)
